package com.xnx3.kefu.chat.controller;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.SafetyUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.kefu.core.bean.ChatUserBean;
import com.xnx3.kefu.core.entity.Zuoxi;
import com.xnx3.kefu.core.service.KefuService;
import com.xnx3.kefu.core.util.SocketUtil;
import com.xnx3.kefu.core.util.TokenUtil;
import com.xnx3.kefu.core.util.UserUtil;
import com.xnx3.kefu.chat.vo.UserVO;
import io.netty.channel.Channel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 用户相关
 * @author 管雷鸣
 */
@Controller(value="kefuChatUserController")
@RequestMapping("/kefu/chat/user/")
public class UserController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private SqlService sqlService;
	@Resource
	private KefuService kefuService;

	
	/**
	 * layim登录成功后的初始化接口
	 * <p>针对layim开放的接口，此接口在kefu.js中未有使用</p>
	 * @return
	 */
	@RequestMapping(value="friendList.json", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject friendList(HttpServletRequest request,
			@RequestParam(value = "token", required = false , defaultValue="") String token){
		String id = null;
		String nickname = null;
		String sign = "";
		String head = null;
		
		com.xnx3.j2ee.entity.User user = getUser();
		
		//token绑定uid
		ChatUserBean userBean = new ChatUserBean();
		userBean.setUser(user);
//		TokenUtil.bind(token, userBean);
		TokenUtil.bind(token, userBean);
		
		ConsoleUtil.log("layim imit - token bind,  token:"+token+", user:"+userBean);
		
		
		if(user == null){
			ChatUserBean youkeUser = TokenUtil.generateYoukeUser(token);
			if(token.indexOf("youke_") != 0){
				token = "youke_"+token;
			}
			id = youkeUser.getChatid();
			nickname = youkeUser.getNickname();
			head = youkeUser.getHead();
		}else{
			id = kefuService.getZuoxiidByUserid(user.getId());
			nickname = user.getNickname();
			sign = user.getSign();
			head = userService.getHead(user);
		}
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "");
		
		JSONObject data = new JSONObject();
		
		JSONObject mine = new JSONObject();
		mine.put("username", nickname);
		mine.put("id", id);
		mine.put("status", "online");
		mine.put("sign", sign);
		mine.put("avatar", head);
		data.put("mine", mine);
		
		JSONArray friendArray = new JSONArray();
		
		JSONObject friend = new JSONObject();
		friend.put("groupname", "沟通列表");
		friend.put("id", 1);
		friend.put("online", 2);
		
		JSONArray UserArray = new JSONArray();
		List<com.xnx3.j2ee.entity.User> userList = sqlService.findAll(com.xnx3.j2ee.entity.User.class);
		for (int i = 0; i < userList.size(); i++) {
			JSONObject userJson = new JSONObject();
			com.xnx3.j2ee.entity.User u = userList.get(i);
			userJson.put("username", u.getNickname());
			userJson.put("id", u.getId());
			userJson.put("avatar", userService.getHead(u));
			userJson.put("sign", u.getSign());
			UserArray.add(userJson);
		}
		List<ChatUserBean> onlineList = SocketUtil.getOnlineUser();
//		for (int i = 0; i < onlineList.size(); i++) {
//			JSONObject userJson = new JSONObject();
//			com.xnx3.kefu.core.vo.bean.User u = onlineList.get(i);
//			userJson.put("username", u.getNickname());
//			userJson.put("id", u.getId());
//			userJson.put("avatar", Global.youkeHead);
//			userJson.put("sign", "无");
//			UserArray.add(userJson);
//		}
		friend.put("list", UserArray);
		
		friendArray.add(friend);
		data.put("friend", friendArray);
		json.put("data", data);
		return json;
	}
	
	

	/**
	 * 登录成功后的初始化接口
	 * @param token 当前操作用户的唯一标识 <required>
	 * 				<p>可通过 调用kefu.js中的函数 kefu.token.get();来获得 </p>
	 */
	@RequestMapping(value="init.json", method = RequestMethod.POST)
	@ResponseBody
	public UserVO init(HttpServletRequest request,
			@RequestParam(value = "token", required = true) String token){
		UserVO vo = new UserVO();
		ChatUserBean chatUser = null;
		com.xnx3.j2ee.entity.User dbUser = getUser();
		if(dbUser == null){
			//未登录的游客，游客发起咨询的
			String chatid = TokenUtil.getChatid(token);
			if(chatid == null){
				//缓存中没有，那就生成一个
				chatUser = TokenUtil.generateYoukeUser(token);
				//将生成的进行缓存
				TokenUtil.bind(token, chatUser);
			}else{
				//缓存中有，那么从缓存中取
				chatUser = UserUtil.getUser(chatid);
			}
		}else{
			chatUser = new ChatUserBean();
			chatUser.setUser(dbUser);
		}
		
		vo.setUser(chatUser);
		return vo;
	}
	
	/**
	 * 通过chatid获取 聊天用户的信息
	 * @param id user.chatid
	 * @return 如果取不到，那么new一个新的 {@link ChatUserBean} 返回
	 */
	@RequestMapping(value="getUserById.json", method = RequestMethod.POST)
	@ResponseBody
	public UserVO getUserById(HttpServletRequest request,
			@RequestParam(value = "id", required = true) String id){
		UserVO vo = new UserVO();
		ChatUserBean chatUser = UserUtil.getUser(id);
		if(chatUser != null){
			//有用户，那么判断一下用户当前是否在线
			List<Channel> channelList = SocketUtil.getChannel(chatUser.getChatid());
			vo.setOnlineState(channelList.size() == 0? "离线":"在线");
		}else{
			chatUser = TokenUtil.generateYoukeUser(null);
		}
		
		vo.setUser(chatUser);
		return vo;
	}
	
	/**
	 * 更新用户昵称，这里更多是给游客进行更改。 坐席的昵称是在坐席后台进行更改
	 * @param token 当前操作用户的唯一标识 <required>
	 * 				<p>可通过 调用kefu.js中的函数 kefu.token.get();来获得 </p>
	 * @param nickname 要修改为的用户昵称。这里改成什么，客服后台看到的这个访客的昵称就叫什么
	 * @return 操作结果
	 */
	@RequestMapping(value="updateNickname.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO updateNickname(HttpServletRequest request,
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "nickname", required = true) String nickname){
		if(nickname.length() < 1) {
			return error("请输入用户要更改为的昵称");
		}
		if(nickname.length() > 20) {
			return error("用户昵称太长，请传入20个以内的字符");
		}
		nickname = SafetyUtil.xssFilter(nickname);
		
		String chatid = TokenUtil.getChatid(token);
		if(chatid == null || chatid.length() < 5) {
			return error("未发现当前用户的chatid");
		}
		ChatUserBean chatUserBean = UserUtil.getUser(chatid);
		if(chatUserBean == null) {
			return error("异常，未找到改用户信息");
		}
		
		//进行更新
		chatUserBean.setNickname(nickname);
		UserUtil.updateUser(chatid, chatUserBean);
		
		return success();
	}
	
	
//	会被xss攻击，所以暂时不加
//	/**
//	 * 更新用户头像，这里更多是给游客进行更改。 坐席的头像是在坐席后台进行更改
//	 * @param token 当前用户的token标识（sessionid）
//	 * @param head 要修改为的用户头像的url绝对路径网址，传入如 https://xxxx.com/a.jpg
//	 */
//	@RequestMapping(value="updateHead${api.suffix}", method = RequestMethod.POST)
//	@ResponseBody
//	public BaseVO updateHead(HttpServletRequest request,
//			@RequestParam(value = "token", required = false , defaultValue="") String token,
//			@RequestParam(value = "head", required = false , defaultValue="") String head){
//		if(head.length() < 1) {
//			return error("请输入用户要更改为的昵称");
//		}
//		if(head.length() < 200) {
//			return error("用户头像url太长");
//		}
////		head = SafetyUtil.xssFilter(head);
//		
//		String chatid = TokenUtil.getChatid(token);
//		if(chatid == null || chatid.length() < 5) {
//			return error("未发现当前用户的chatid");
//		}
//		ChatUserBean chatUserBean = UserUtil.getUser(chatid);
//		if(chatUserBean == null) {
//			return error("异常，未找到改用户信息");
//		}
//		
//		//进行更新
//		chatUserBean.setHead(head);
//		UserUtil.updateUser(chatid, chatUserBean);
//		
//		return success();
//	}
}
